package com.cqs.learning.jvm;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.*;

/**
 * -XX:NewRatio=2 -XX:SurvivorRatio=8 -XX:+PrintGCDateStamps -XX:+PrintGCDetails  -Xloggc:./gc.log -Xmx128M -Xms128M
 *
 * @author lixw
 * @date 2020/3/15 8:14
 */
public class GcDemo {

    public static void main(String[] args) {
        f2();
    }



    private static void f2() {
        int c = 0;
        while (true){
            calculate2();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (++c % 100 == 0){
                System.out.println("计数器:" + c);
            }
        }
    }
    private static void f1() {
        int c = 0;
        while (true){
            calculate();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (++c % 100 == 0){
                System.out.println("计数器:" + c);
            }
        }
    }

    private static void calculate(){
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(new Runnable() {
            @Override
            public void run() {
                File file = new File("tmp.txt");
                if (file.exists()){
                    file.delete();
                }else {
                    try (FileOutputStream stream = new FileOutputStream(file);){

                        stream.write("1234e".getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
    }

    private static void calculate2(){
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 10L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1));
        executor.submit(new Runnable() {
            @Override
            public void run() {
                File file = new File("tmp.txt");
                if (file.exists()){
                    file.delete();
                }else {
                    try (FileOutputStream stream = new FileOutputStream(file);){

                        stream.write("1234e".getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
    }

}
